import * as THREE from 'three'
import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader'

export function fnRgbRender (scene: THREE.Scene) {
  new RGBELoader().loadAsync('/textures/hdr.hdr').then((texture) => {
    texture.mapping = THREE.EquirectangularReflectionMapping
    // 将加载的材质texture设置给背景和环境
    // scene.background = texture
    scene.environment = texture
    console.log('xxxxxxxxxxxx')
  })

  // const pmremGenerator = new THREE.PMREMGenerator(renderer)
  // pmremGenerator.compileEquirectangularShader()// 阴影
  // const loader = new RGBELoader()
  // loader.setDataType(THREE.UnsignedByteType)
  // pmremGenerator.compileEquirectangularShader()

  // loader.load('/textures/hdr.hdr', texture => {
  //   const envMap = pmremGenerator.fromEquirectangular(texture).texture
  //   scene.environment = envMap // 给场景添加环境光效果
  //   // scene.background = envMap // 给场景添加背景图
  //   // pmremGenerator.dispose()
  //   console.log('-------------------')
  // })
}

/**
 * 该函数限制输入框仅能输入数字
 * @param define  可传入自定义逻辑
 * @returns (event: InputEvent) => void
 */
export const createFnValue = (define?: Map<string, (target: HTMLInputElement, data?: string) => void>) => {
  let prevState = ''
  let deleteVal = false
  const fnState = define ?? new Map([
    ['insertFromPaste', (target: HTMLInputElement) => {
      if (/^\d*$/.test(target.value)) {
        prevState = target.value
      } else {
        target.value = prevState
      }
    }],
    ['insertCompositionText', (target: HTMLInputElement) => {
      deleteVal = true
      target.value = prevState
    }],
    ['deleteByCut', (target: HTMLInputElement) => {
      prevState = target.value
    }],
    ['deleteContentBackward', (target: HTMLInputElement) => {
      if (deleteVal) {
        deleteVal = false
      } else {
        prevState = target.value
      }
    }],
    ['insertText', (target: HTMLInputElement, data: string) => {
      if (/^\d$/.test(data)) {
        prevState = target.value
      } else {
        target.value = prevState
      }
    }]
  ])
  return (event: InputEvent) => {
    const { inputType, target, data } = event
    const fn = fnState.get(inputType)
    if (typeof fn === 'function') fn(target as HTMLInputElement, data as string)
  }
}

export function getSelectedText () {
  const selection = window.getSelection()
  return selection ? selection.toString() : ''
}
